//
//  ShowPhotoViewController.m
//  YunGui
//
//  Created by Hanen 3G 01 on 16/4/22.
//  Copyright © 2016年 hanen. All rights reserved.
//

#import "ShowPhotoViewController.h"
#import "RuleViewController2.h"
#import "ShowImageScrollView.h"
#import "MyImageView.h"
#import "PopTipView.h"
#import "QBImagePickerController.h"
#import "CameraViewController.h"
#import "NetModel.h"
#import "ResultsViewController.h"
#import "UIButton+WebCache.h"
#import "PhontoCollectionCell.h"
//#define RandColor [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1.0]
@interface ShowPhotoViewController ()<UIScrollViewDelegate,PopTipViewDelegate,QBImagePickerControllerDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
    
    UIView *navView ;
    UIView *bottom;
    CGFloat space;
    ShowImageScrollView    *_imageScrollView;
    UICollectionView  *_collectionView;
    UILabel                *_indexLabel;
    
    ShowImageScrollView    *_smallImageScrollView;
    UIButton *lastAddBtn ;
      CGFloat  lastMaxX;
    MyImageView *selectedImageView;
//    BOOL  imageSelected;
    CGFloat smallImageW;
    PopTipView *popTips;//是否删除照片的
    PopTipView *popChooseCamera;
    
      NSMutableArray  *_choosePicDataArray;
    
    CGFloat spaceNum;
    CGFloat imageW ;
    CGFloat imageH ;

     dispatch_queue_t _globleQueue;//全局队列

    BOOL  isRetoke;
    
    BOOL  isRecieveMemeriFlag;//如果有内存警告的话 则不在初始化视图的过程中 再次上传图片
}
@end

@implementation ShowPhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    self.view.opaque = YES;
    self.navigationController.navigationBarHidden = YES;
      [self setNeedsStatusBarAppearanceUpdate];
     space = [UIView getWidth:8.0f];

    //获取全局队列
    _globleQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    [self addNav];
    isRetoke = NO;
    [self addCollectionView];
//    [self addShowView];
    [self addSmallShowView];
}

- (void)viewWillDisappear:(BOOL)animated
{
//        [SVProgressHUD showWithStatus:@"图片传输中"];
//    for (int i = 0; i < self.imageArr.count ; i++) {
//        id type = self.imageArr[i];
//        if ([type isKindOfClass:[ImageModel class]]) {
//            continue;
//        }else if ([type isKindOfClass:[NSData class]]){
//            
//            dispatch_sync(_globleQueue, ^{
//            
//                NSIndexPath *index = [NSIndexPath indexPathForItem:i inSection:0];
//                [self upLoadImageFirstWithIndexPath:index];
//                if(i == self.imageArr.count - 1){
//                        [SVProgressHUD dismiss];
//                }
//            });
//        }
//    }
//    [SVProgressHUD dismiss];
}
- (void)viewWillAppear:(BOOL)animated
{
//    self.navigationControll
    self.navigationController.navigationBarHidden = YES;
//    for (MyImageView *vi in _imageScrollView.subviews) {
//        if(vi.iamgeID){
//        NSLog(@"图片的id  %@",vi.iamgeID);
//     }
//    }

//    for (int i = 0; i< self.imageArr.count; i++) {
//        MyImageView *imageV = [_imageScrollView viewWithTag:889974 + i];
//         NSLog(@"图片的id  %@",imageV.iamgeID);
//    }
}
- (void)addNav
{
   navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, [UIView getHeight:45.0f])];
    navView.backgroundColor = BackPurColor;
        [self.view addSubview:navView];
    navView.opaque = YES;
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, 24 + (navView.height - 24 )/ 2.0f - 25.0f / 2.0f, 25, 25)];
    backBtn.opaque = YES;
//    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
//    backBtn.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [navView addSubview:backBtn];
    [backBtn addTarget:self action:@selector(backToLastView) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    
    bottom = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - [UIView getHeight:60.0f], kScreenWidth, [UIView getHeight:60.0f])];
    bottom.opaque = YES;
    bottom.backgroundColor = BackPurColor;
  
    [self.view addSubview:bottom];
    
    UIButton *ruleBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, bottom.height / 2.0f - 25 /2.0f, 25, 25)];
    ruleBtn.opaque = YES;
    [ruleBtn setBackgroundImage:[UIImage imageNamed:@"xuanzexiangce1.png"] forState:UIControlStateNormal];
//    [ruleBtn setTitle:@"标准" forState:UIControlStateNormal];
    [ruleBtn addTarget:self action:@selector(jumpToRule) forControlEvents:UIControlEventTouchUpInside];
//    ruleBtn.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    
    [bottom addSubview:ruleBtn];
    
    
    UIButton *retakenBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.centerX - 15, bottom.height / 2.0f - 15, 60, 30)];
    retakenBtn.opaque = YES;
    retakenBtn.center = CGPointMake(self.view.width / 2.0, bottom.height / 2.0f);
    [retakenBtn setTitle:@"重拍" forState:UIControlStateNormal];
    [retakenBtn addTarget:self action:@selector(reTakePhoto) forControlEvents:UIControlEventTouchUpInside];
    retakenBtn.titleLabel.font = [UIFont systemFontOfSize:18.0f];

    [bottom addSubview:retakenBtn];
    
    CGFloat btnW = 70.0f;
    CGFloat btnH = 70 *103 / 198;
    UIButton *checkBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.width - 20 - 70 , bottom.height / 2.0f - btnH /2.0, btnW, btnH)];
    checkBtn.opaque = YES;
//    [checkBtn setTitle:@"评定" forState:UIControlStateNormal];
    [checkBtn addTarget:self action:@selector(judgeCheck) forControlEvents:UIControlEventTouchUpInside];
    [checkBtn setBackgroundImage:[UIImage imageNamed:@" pingdinganniu .png"] forState:UIControlStateNormal];
//    checkBtn.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    checkBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    checkBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    [bottom addSubview:checkBtn];
    
    
}
#pragma mark --评定
- (void)judgeCheck
{
//     _choosePicDataArray = [NSMutableArray array];
    if (self.imageArr.count < self.upLoadNumber) {
        [Tools showMessage:[NSString stringWithFormat:@"最少上传%d张照片哦",self.upLoadNumber] view:self];
        return;
    }else{
//          [SVProgressHUD showWithStatus:@"图片上传中"];
//        dispatch_sync(_globleQueue, ^{
//           [self upLoadImageFirst];
//        
//        });
//    NSLog(@"上传的个数 %ld",_uploadArr.count);
//                dispatch_sync(_globleQueue, ^{
//                    [self upLoadImageSecond];
//    });
          if(self.imageArr.count != 0){
        int  a = 0;
        for (int i = 0; i < self.imageArr.count ; i++) {
            id type = self.imageArr[i];
            if ([type isKindOfClass:[ImageModel class]]) {
                a ++;
            }else if ([type isKindOfClass:[NSData class]]){
                [Tools showMessage:@"请等待图片上传完成" view:self];
                return;
            }
            if (i == self.imageArr.count - 1) {
                if (self.imageArr.count == a) {
                    ResultsViewController *judgeVC = [[ResultsViewController alloc] init];
                    judgeVC.checkType = self.checkType;
                    judgeVC.checklID = self.checkID;
                    [self.navigationController pushViewController:judgeVC animated:YES];
                }
            }
        }
          }
        
    }
}
- (void)upLoadImageFirstWithIndexPath:(NSIndexPath *)indexpath
{
    NSLog(@"indexpath 上传第一次 走了几遍 %@",indexpath);
//    for (int i = 0; i< self.imageArr.count; i++) {
//        NSLog(@"imageArr[i]的类型  %@",self.imageArr[i]);
//    }
//    [_uploadArr removeAllObjects];
//    int alreadHadImageNum = 0;
//    [SVProgressHUD showWithStatus:@"图片传输中"];
    
//    for (int i =0 ; i<self.imageArr.count; i++) {
//        id object = self.imageArr[i];
////        NSLog(@"%@",[object class]);
//    }
//    MyImageView *imagev;
//    for (int i = 0; i< self.imageArr.count; i++) {
//         NSLog(@"图片大小%lu",(unsigned long)[self.imageArr[i] length]);
//       imagev = [_imageScrollView viewWithTag:889974 + i];
    
//        NSString *numStr = imagev.fileName;
//#warning 判断图片上的NSnumber 为空的避免 重复上传 上传过的图片
//        NSString *numStr = [NSString stringWithFormat:@"%d",[imagev.iamgeID intValue]];
    
//          NSLog(@"imagev.fileName %@ ",numStr);
//        if ([self.imageArr[i] isKindOfClass:[ImageModel class]] || imagev.fileName) {
//            alreadHadImageNum ++;
//            NSLog(@"%d ++++++++123321123321",alreadHadImageNum);
            
//        }else{
    
//            NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
//            [dictionary setObject:@"app.upload.store" forKey:@"method"];
//            [dictionary setObject:@"jpeg" forKey:@"type"];
//            [dictionary setObject:self.imageArr[i] forKey:@"data"];
            
        
        [DataTool uploadPic:self.imageArr[indexpath.item] success:^(id data) {
            [SVProgressHUD dismiss];
//            NSLog(@"data %@",data);
//            NSLog(@"图片大小%lu",(unsigned long)[self.imageArr[i] length]);
            if ([data[@"status"] isEqualToString:@"ERROR"]) {
                [Tools showMessage:data[@"msg"] view:self];
                return ;
            }else if ([data[@"status"] isEqualToString:@"SUCCESS"]) {
                //                [SVProgressHUD dismiss];
                [self upLoadImageSecondWithPath:data[@"data"][@"pic"] WithIndexPath:indexpath];
            }
//            NSLog(@"状态%@",data[@"status"]);
//            [_uploadArr addObject:data[@"data"][@"pic"]];
//            NSLog(@"上传的个数 %ld",_uploadArr.count);
            
        } fail:^(NSError *error) {
            NSLog(@"%@",error);
        }];
  
}
- (void)upLoadImageSecondWithPath:(NSString *)imagePath WithIndexPath:(NSIndexPath *)indexPath
{
     NSLog(@"indexpath 上传第二次 走了几遍 %@",indexPath);
//    NSLog(@"上传的个数 %ld",(unsigned long)_uploadArr.count);
//    if (_uploadArr.count != 0) {
         [SVProgressHUD showWithStatus:@"图片传输中"];
//      NSDictionary *dd =  [[NSUserDefaults standardUserDefaults] objectForKey:@"checkDict"];
//        NSString *picStr = [NSString stringWithFormat:@"%@",[_uploadArr componentsJoinedByString:@","]];
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:@{@"method":@"app.branchCheck.upload.img",@"images": imagePath}];
        if (self.checkType) {
            [dict setObject: self.checkDetailId forKey:@"detail_id"];
        }
        //            [talkingArray removeAllObjects];
        NSDictionary *paramersDict = [DataTool addSignToDic:dict];
        
//        NSLog(@"paramersDict 参数%@",paramersDict);
        [DataTool postWithUrl:HEAD_URL parameters:paramersDict success:^(id data) {
            id backData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers error:nil];
            NSLog(@"图片上传返回的数据%@",backData);
            
//            for (int i = 0; i < _uploadArr.count; i++) {
//                MyImageView *image = [_imageScrollView viewWithTag:889974 + i + self.imageArr.count - _uploadArr.count];
//                if (!image.iamgeID) {
//                    
//                }
            
//                image.iamgeID = dict[@"id"];
//                image.imageUrl = dict[@"url"];
//                image.fileName = dict[@"file_name"];
            if([backData[@"status"] isEqualToString:@"SUCCESS"]){
                NSArray *arr = backData[@"data"][@"imgData"];
                NSDictionary *dict = arr.firstObject;
                ImageModel *model = [[ImageModel alloc] init];
                model.imageId = dict[@"id"];
                model.url = dict[@"url"];
                model.file_name = dict[@"file_name"];
                [model setValuesForKeysWithDictionary:dict];
                [self.imageArr replaceObjectAtIndex:indexPath.item withObject:model];
                NSLog(@"数组的类型%@",[self.imageArr[indexPath.item] class]);
                  [SVProgressHUD dismiss];
//                [_collectionView reloadData];
            }


        } fail:^(NSError *error) {
            NSLog(@"%@",error.localizedDescription);
            [Tools showMessage:error.localizedDescription view:self];
            [SVProgressHUD dismiss];
//            ResultsViewController *judgeVC = [[ResultsViewController alloc] init];
//            judgeVC.checkType = self.checkType;
//            [self.navigationController pushViewController:judgeVC animated:YES];
        }];
        [SVProgressHUD dismiss];
    
    [_collectionView reloadData];
//    }else{
////            [SVProgressHUD dismiss];
//    }
   
#warning 咱做测试
//    ResultsViewController *judgeVC = [[ResultsViewController alloc] init];
//    judgeVC.checkType = self.checkType;
//    [self.navigationController pushViewController:judgeVC animated:YES];

}
//- (void)viewWillAppear:(BOOL)animated
//{
//    self.navigationController.navigationBarHidden = NO;
//}
//中间展示页面

- (void)addCollectionView
{
    CGFloat scrollH ;
    if (kScreenHeight == 480) {
        scrollH = 300.0f;
        spaceNum  = 7.0f;
    }else{
        scrollH =  [UIView getHeight:350.0f];
        spaceNum  = 5.0f;
    }
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 0;
    [layout  setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, navView.maxY, kScreenWidth, scrollH) collectionViewLayout:layout];
    _collectionView.pagingEnabled = YES;
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor blackColor];
    _collectionView.opaque = YES;
    
    [_collectionView registerClass:[PhontoCollectionCell class] forCellWithReuseIdentifier:[PhontoCollectionCell identifier]];
    
    [self.view addSubview:_collectionView];
    
     _collectionView.contentOffset = CGPointMake(_collectionView.width * (self.imageArr.count - 1), 0);
    
     NSString *str = [NSString stringWithFormat:@"%.0f/%ld",floorf( _collectionView.contentOffset.x / _collectionView.width) + 1,(unsigned long)self.imageArr.count];
    _indexLabel = [ViewTool getLabelWith:CGRectMake(kScreenWidth / 2.0f - 30, _collectionView.maxY - 20 , 60, 20) WithTitle:str WithFontSize:14.0f WithTitleColor:[UIColor whiteColor] WithTextAlignment:NSTextAlignmentCenter];
    ////    _indexLabel.backgroundColor = BlueColor;
        [self.view addSubview:_indexLabel];
    
    
    
    for (int i = 0; i < self.imageArr.count ; i++) {
        
        id type = self.imageArr[i];
        if ([type isKindOfClass:[ImageModel class]]) {
            
        }else if ([type isKindOfClass:[NSData class]]){
            if (isRecieveMemeriFlag) {
                return;
            }else{
            dispatch_sync(_globleQueue, ^{
                  [SVProgressHUD showWithStatus:@"图片上传中"];
                NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
                
                NSLog(@"%@",indexPath);
                //                      [SVProgressHUD showWithStatus:@"图片传输中"];
                [self upLoadImageFirstWithIndexPath:indexPath];
            });
            }
        }
        if(i == self.imageArr.count - 1){
            [_collectionView reloadData];
////            _collectionView.contentSize = CGSizeMake(kScreenWidth * self.imageArr.count, _collectionView.height);
//            [SVProgressHUD dismiss];
        }
    }
    
    if(self.imageArr.count != 0){
        int  a = 0;
        for (int i = 0; i < self.imageArr.count ; i++) {
            id type = self.imageArr[i];
            if ([type isKindOfClass:[ImageModel class]]) {
                a ++;
            }else if ([type isKindOfClass:[NSData class]]){
                
                continue;
            }
            if (i == self.imageArr.count - 1) {
                if (self.imageArr.count == a) {
                      [_collectionView reloadData];
                }
            }
        }
        
    }
    

}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
//    NSLog(@"%ld",_imageArr.count);
    return _imageArr.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PhontoCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[PhontoCollectionCell identifier] forIndexPath:indexPath];
//    cell.backgroundColor = RandColor;
    if (self.imageArr.count != 0) {
        
   id  imageArrType = self.imageArr[indexPath.item];
    if ([imageArrType isKindOfClass:[ImageModel class]]) {
        NSLog(@"有图片的情况下 打印图片地址%@",[(ImageModel *)imageArrType url]);
        NSString *urlStr = [(ImageModel *)imageArrType url];
        //                 NSString *urlStr = [[(ImageModel *)imageArrType url] stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
        [cell.imgaeView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:nil];//
        //                            [imageview sd_setImageWithURL:[NSURL URLWithString:@"http://test.yun-gui.com/tools/show?path=images/app/2016/5/2/146218444022580.jpg"] placeholderImage:nil];
        cell.imgaeView.iamgeID = [(ImageModel *)imageArrType imageId];
        cell.imgaeView.fileName = [(ImageModel *)imageArrType file_name];
        cell.imgaeView.imageUrl = [(ImageModel *)imageArrType url];
    }
//        //            NSData *data23 = imageArrType[i
//      UIImage *  iamge = [UIImage imageWithData:imageArrType];
//        cell.imgaeView.image = iamge;
//        [self upLoadImageFirstWithIndexPath:indexPath];
//       cell.imgaeView.
//    }
    
//    imageview.tag = 889974 + i;
    //        __unsafe_unretained
    __weak ShowPhotoViewController *shw = self;
    cell.imgaeView.block = ^(MyImageView *imageVie,BOOL isSelfSelected){
        popTips = [[PopTipView alloc] initWithFrame:CGRectMake(0, 0, [UIView getWidth:200], [UIView getHeight:120.0f])];
        popTips.tipsLabel.text = @"是否删除照片?";
        popTips.delegate = self;
        popTips.righTitle  = @"删除";
        popTips.leftTitle = @"取消";
        [popTips.leftButton setTitleColor:GRAYCOLOR forState:UIControlStateNormal];
        popTips.isShowImage = NO;
        [popTips showToView:shw.view];
        selectedImageView = imageVie;
     
    };
        
    }
    
    return cell;
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(collectionView.width, collectionView.height);
}

//- (void)addShowView
//{
//    CGFloat scrollH ;
//    if (kScreenHeight == 480) {
//        scrollH = 300.0f;
//         spaceNum  = 7.0f;
//    }else{
//        scrollH =  [UIView getHeight:350.0f];
//        spaceNum  = 5.0f;
//    }
//    _imageScrollView = [[ShowImageScrollView alloc] initWithFrame:CGRectMake(0, navView.maxY, kScreenWidth, scrollH)];
//    _imageScrollView.delaysContentTouches = YES;
//    _imageScrollView.canCancelContentTouches = NO;
//    _imageScrollView.pagingEnabled = YES;
//    _imageScrollView.delegate = self;
//    _imageScrollView.backgroundColor = [UIColor blackColor];
//    [self.view addSubview:_imageScrollView];
////     spaceNum;//有几个 space的间距宽度
////    dispatch_async(_myQueue, ^{
//
//        imageW = _imageScrollView.width  - spaceNum * 2 * space;
//        
//        imageH = imageW * 1000 / 800 ;
//    UIImage *iamge;
//        for (int i = 0; i < self.imageArr.count; i ++) {
//            
//            MyImageView *imageview = [[MyImageView alloc] initWithFrame:CGRectMake(spaceNum *space + (_imageScrollView.width) * i, 2 *space , imageW, imageH)];
//            //        imageview.backgroundColor = [UIColor orangColor];
//            id imageArrType = nil;
//            @autoreleasepool {
//                 imageArrType = self.imageArr[i];
//            }
//            //        NSLog(@"%@",imageArrType);
//            if ([imageArrType isKindOfClass:[ImageModel class]]) {
//                NSLog(@"有图片的情况下 打印图片地址%@",[(ImageModel *)imageArrType url]);
//                NSString *urlStr = [(ImageModel *)imageArrType url];
////                 NSString *urlStr = [[(ImageModel *)imageArrType url] stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
//                [imageview sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:nil];//
////                            [imageview sd_setImageWithURL:[NSURL URLWithString:@"http://test.yun-gui.com/tools/show?path=images/app/2016/5/2/146218444022580.jpg"] placeholderImage:nil];
//                imageview.iamgeID = [(ImageModel *)imageArrType imageId];
//                imageview.fileName = [(ImageModel *)imageArrType file_name];
//                imageview.imageUrl = [(ImageModel *)imageArrType url];
//            }else{
//                //            NSData *data23 = imageArrType[i
//               iamge = [UIImage imageWithData:imageArrType];
//                imageview.image = iamge;
//            }
//            
//            imageview.tag = 889974 + i;
//            //        __unsafe_unretained
//            __weak ShowPhotoViewController *shw = self;
//            imageview.block = ^(MyImageView *imageVie,BOOL isSelfSelected){
//                popTips = [[PopTipView alloc] initWithFrame:CGRectMake(0, 0, [UIView getWidth:200], [UIView getHeight:120.0f])];
//                popTips.tipsLabel.text = @"是否删除照片?";
//                popTips.delegate = self;
//                popTips.righTitle  = @"删除";
//                popTips.leftTitle = @"取消";
//                [popTips.leftButton setTitleColor:GRAYCOLOR forState:UIControlStateNormal];
//                popTips.isShowImage = NO;
//                [popTips showToView:shw.view];
//                selectedImageView = imageVie;
//                //            imageSelected = isSelfSelected;
//            };
//            
////            dispatch_async(dispatch_get_main_queue(), ^{
//                [_imageScrollView addSubview:imageview];
////            });
//
//        }
//          [self upLoadImageFirst];
//        
////    });
//    
//   
//    _imageScrollView.contentSize = CGSizeMake(_imageScrollView.width * self.imageArr.count, _imageScrollView.height);
//     _imageScrollView.contentOffset = CGPointMake(_imageScrollView.width * (self.imageArr.count - 1), 0);
//    
//    NSString *str = [NSString stringWithFormat:@"%.0f/%ld",floorf( _imageScrollView.contentOffset.x / _imageScrollView.width) + 1,(unsigned long)self.imageArr.count];
//    _indexLabel = [ViewTool getLabelWith:CGRectMake(kScreenWidth / 2.0f - 30, _imageScrollView.maxY - 20 , 60, 20) WithTitle:str WithFontSize:14.0f WithTitleColor:[UIColor whiteColor] WithTextAlignment:NSTextAlignmentCenter];
////    _indexLabel.backgroundColor = BlueColor;
//    [self.view addSubview:_indexLabel];
//    
//
//    
//}

- (void)addSmallShowView
{
    CGFloat smallSpace = 5.0f;
    
    smallImageW = (kScreenWidth - (self.imageArr.count * smallSpace)) / 4.0f;
    if(smallImageW < 30.0f){
        smallImageW = 30.0f;
    }
    _smallImageScrollView = [[ShowImageScrollView alloc] initWithFrame:CGRectMake(0, self.view.height - bottom.height - smallImageW, self.view.width, smallImageW)];
    //    _smallImageScrollView.delaysContentTouches = YES;
    //    _smallImageScrollView.canCancelContentTouches = NO;
    _smallImageScrollView.pagingEnabled = YES;
    _smallImageScrollView.delegate = self;
    _smallImageScrollView.backgroundColor = [UIColor blackColor];
    _smallImageScrollView.opaque = YES;
    _smallImageScrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_smallImageScrollView];
    
    
    UIButton *btn;
    UIImage *iamge;
    for (int i = 0; i < self.imageArr.count; i ++) {
        btn = [[UIButton alloc] initWithFrame:CGRectMake((smallImageW  + smallSpace) * i, 0, smallImageW, smallImageW)];
        //        btn.backgroundColor = [UIColor orangeColor];
        btn.opaque = YES;
        id  imageArrType = self.iamgeSmallArr[i];
        if ([imageArrType isKindOfClass:[ImageModel class]]) {
            [btn sd_setBackgroundImageWithURL:[NSURL URLWithString:[(ImageModel *)imageArrType url]] forState:UIControlStateNormal];
        }else{
             iamge = [UIImage imageWithData:self.iamgeSmallArr[i]];
            [btn setBackgroundImage:iamge forState:UIControlStateNormal];
        }
        
                btn.tag = 76445 + i;
        //        imageview.image = iamge;
        [_smallImageScrollView addSubview:btn];
        [btn addTarget:self action:@selector(clickSmallImage:) forControlEvents:UIControlEventTouchUpInside];
        if (i == self.iamgeSmallArr.count - 1) {
            lastMaxX = btn.maxX;
        }
        //        if (imageview.maxX > _smallImageScrollView.width) {
        //             _smallImageScrollView.contentOffset = CGPointMake(smallImageW * (self.imageArr.count - 1), 0);
        //        }
    }
    
    lastAddBtn = [[UIButton alloc] initWithFrame:CGRectMake(lastMaxX  + smallSpace, 0 , smallImageW, smallImageW)];
    lastAddBtn.opaque = YES;
    lastAddBtn.backgroundColor = GrayBackColor;
    //    UIImage *iamge = [UIImage imageWithData:self.imageArr[i]];
    [lastAddBtn setBackgroundImage:[UIImage imageNamed:@"Btn_Normal_paizhangpian.png"] forState:UIControlStateNormal];
    [lastAddBtn addTarget:self action:@selector(addPicture) forControlEvents:UIControlEventTouchUpInside];
    
    //        imageview.image = iamge;
    [_smallImageScrollView addSubview:lastAddBtn];
    _smallImageScrollView.contentSize = CGSizeMake((5.0f + smallImageW) * (self.iamgeSmallArr.count + 1) + smallSpace , _smallImageScrollView.height);
    //    lastAddBtn.frame = CGRectMake(lastMaxX  + smallSpace, 0 , smallImageW, smallImageW);
//    _smallImageScrollView.contentOffset = CGPointMake(smallImageW * (self.iamgeSmallArr.count - 2), 0);
}
#pragma mark --点击确定或删除
- (void)clickLeftbtnWith:(PopTipView *)popView{
    if (popView == popTips) {
           [popTips dimiss];
    }

    
    if(popView == popChooseCamera){//选择相机 加一个图
        [popChooseCamera dimiss];
        if(![Tools isAllowTakePhoto]){
            [Tools showMessage:@"APP无相机访问权限，请先设置!" view:self];
            return;
        }
//        if (self.chooseType == 2) {//页面先从 相册选择进来 要进入 相机
       
            CameraViewController *cameraVC = [[CameraViewController alloc] init];
            //        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:cameraVC];
            cameraVC.isShouldBack = YES; //返回了
            cameraVC.checkType = self.checkType;
            cameraVC.branchId = self.branchId;
            cameraVC.checkId = self.checkID;
            cameraVC.isPush = NO;
            [self presentViewController:cameraVC animated:YES completion:nil];
            cameraVC.backBlock = ^(NSData *data,NSData *data1){
                if (isRetoke == NO) {
                        NSLog(@"加入职前self.imageArr.count  --%d",self.imageArr.count);
//                    NSLog(@"%@",data1);
//                    MyImageView *imageview = [[MyImageView alloc] initWithFrame:CGRectMake(spaceNum *space + (_imageScrollView.width) * (self.imageArr.count), 2 *space , imageW, imageH)];
                    UIButton *smallbtn = [[UIButton alloc] initWithFrame:CGRectMake((smallImageW  + 5.0f) * self.iamgeSmallArr.count, 0, smallImageW, smallImageW)];
                    smallbtn.opaque = YES;
                    [smallbtn addTarget:self action:@selector(clickSmallImage:) forControlEvents:UIControlEventTouchUpInside];
                    [self.imageArr addObject:data];
                    [self.iamgeSmallArr addObject:data1];
                    //            imageview.backgroundColor = [UIColor orangeColor];
//                    UIImage *iamge1 = [UIImage imageWithData:data];
                    //                NSLog(@"%@",data);
                    UIImage *image2 = [UIImage imageWithData:data1];
                    //               data1 = [self imageWithImage:image2 scaledToSize:CGSizeMake(smallImageW, smallImageW)];
                    
//                    imageview.image = iamge1;
                    smallbtn.backgroundColor = [UIColor orangeColor];
                    [smallbtn setBackgroundImage:image2 forState:UIControlStateNormal];
                    
                    [_smallImageScrollView addSubview:smallbtn];
//                    [_imageScrollView addSubview:imageview];
                    
//                    imageview.tag = 889974 + self.imageArr.count - 1;
                    smallbtn.tag = 76445 + self.iamgeSmallArr.count - 1;
      
              
                    _smallImageScrollView.contentSize = CGSizeMake((smallImageW + 5.0f) * (self.iamgeSmallArr.count +1), smallImageW);
                    [self changeLastBtnFrame];
                    [self refreshIndexText];
//                [_collectionView reloadData];
                    
//                     _collectionView.contentOffset = CGPointMake(_collectionView.width * (self.imageArr.count - 1), 0);
                    _smallImageScrollView.contentOffset = CGPointMake(smallImageW * (self.iamgeSmallArr.count - 1), 0);
//                    [self upLoadImageFirst];//上传
                    NSLog(@"加入之后s self.imageArr.count  --%d",self.imageArr.count);
                    for (int i = 0; i < self.imageArr.count ; i++) {
                        id type = self.imageArr[i];
                        if ([type isKindOfClass:[ImageModel class]]) {
                            
                        }else if ([type isKindOfClass:[NSData class]]){
                            
//                            dispatch_sync(_globleQueue, ^{
                            
                                NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
                                
                                NSLog(@"indexPath 走了几遍%@",indexPath);
                                //                      [SVProgressHUD showWithStatus:@"图片传输中"];
//                                [self upLoadImageFirstWithIndexPath:indexPath];
                            [DataTool uploadPic:self.imageArr[indexPath.item] success:^(id data) {
                                [SVProgressHUD dismiss];
                                //            NSLog(@"data %@",data);
                                //            NSLog(@"图片大小%lu",(unsigned long)[self.imageArr[i] length]);
                                if ([data[@"status"] isEqualToString:@"ERROR"]) {
                                    [Tools showMessage:data[@"msg"] view:self];
                                    return ;
                                }
                                //            NSLog(@"状态%@",data[@"status"]);
                                //            [_uploadArr addObject:data[@"data"][@"pic"]];
                                //            NSLog(@"上传的个数 %ld",_uploadArr.count);
                                if ([data[@"status"] isEqualToString:@"SUCCESS"]) {
                                    //                [SVProgressHUD dismiss];
                                    [self upLoadImageSecondWithPath:data[@"data"][@"pic"] WithIndexPath:indexPath];
                                    isRecieveMemeriFlag = NO;
                                }
                            } fail:^(NSError *error) {
                                NSLog(@"%@",error);
                            }];

//                            });
                        }
//                        if(i == self.imageArr.count - 1){
//                            [_collectionView reloadData];
//                            _collectionView.contentOffset = CGPointMake(_collectionView.width * (self.imageArr.count - 1), 0);
//                            [SVProgressHUD dismiss];
//                        }
                    }
                   
//                    if(self.imageArr.count != 0){
//                        int  a = 0;
//                        for (int i = 0; i < self.imageArr.count ; i++) {
//                            id type = self.imageArr[i];
//                            if ([type isKindOfClass:[ImageModel class]]) {
//                                a ++;
//                            }else if ([type isKindOfClass:[NSData class]]){
//                                
//                                continue;
//                            }
//                            if (i == self.imageArr.count - 1) {
//                                if (self.imageArr.count == a) {
//                                    [_collectionView reloadData];
//                                }
//                            }
//                        }
//                        
//                    }

                }else{//更新一下重拍的
                    [DataTool uploadPic:data success:^(id data) {
                        [SVProgressHUD dismiss];
//                        NSLog(@"data %@",data);
//                        NSLog(@"图片大小%lu",(unsigned long)[data length]);
                        if ([data[@"status"] isEqualToString:@"ERROR"]) {
                            [Tools showMessage:data[@"msg"] view:self];
                            return ;
                        }else{
                            self.pathBlock(data[@"pic"]);
                        }
                        NSLog(@"状态%@",data[@"status"]);

                        
                    } fail:^(NSError *error) {
                        NSLog(@"%@",error);
                    }];
                }
            };
    }
    
    if(self.imageArr.count != 0){
        int  a = 0;
        for (int i = 0; i < self.imageArr.count ; i++) {
            id type = self.imageArr[i];
            if ([type isKindOfClass:[ImageModel class]]) {
                a ++;
            }else if ([type isKindOfClass:[NSData class]]){
                
                continue;
            }
            if (i == self.imageArr.count - 1) {
                if (self.imageArr.count == a) {
                    [_collectionView reloadData];
                }
            }
        }
        
    }

//    [_collectionView reloadData];
//    _collectionView.contentOffset = CGPointMake(_collectionView.width * (self.imageArr.count - 1), 0);
//    [SVProgressHUD dismiss];
}
- (void)clickRightbtnWith:(PopTipView *)popView{
    [popTips dimiss];
    
    if(popView == popTips){//删除 判断
        CGFloat x = _collectionView.contentOffset.x;
        int page = floorf(x / _collectionView.width) ;
 
    
        [_collectionView reloadData];
        
    UIButton *btn = [_smallImageScrollView viewWithTag:76445 + page];
    CGRect smallFrame = btn.frame;
    [btn removeFromSuperview];
 
    if (page == self.imageArr.count - 1) {
        
    }else{
        [self refreshShowWithIndex:page withSmallFrame:smallFrame];
    }
//    NSLog(@"一共数组有%lu个图片，点的是哪一个图片%d",(unsigned long)self.imageArr.count,page);
//      [self.imageArr removeObjectAtIndex:i];
    
    [self.iamgeSmallArr removeObjectAtIndex:page];
    _smallImageScrollView.contentSize = CGSizeMake((smallImageW + 5.0f)* (self.iamgeSmallArr.count + 1) + 5.0f , _smallImageScrollView.height);
          [self changeLastBtnFrame];
           [self refreshIndexText];
        //如果这个图片有自己的id  则需要联服务器删除它
        id mdoel = self.imageArr[page];
        
        if ([mdoel isKindOfClass:[ImageModel class]]) {
            ImageModel *model = mdoel;
             [self removeImageFormNetWith:model.imageId];
            [self.imageArr removeObjectAtIndex:page];
        }
       
    }else if(popView == popChooseCamera){//选择拍照
//        if(self.chooseType == 2){
//            
//        }
        [popChooseCamera dimiss];
        
         [self takePictureInPhone1];
        
    }
   
    
}
- (void)refreshShowWithIndex:(int) i withSmallFrame:(CGRect)smallFrame
{
    for (int j = i; j<self.imageArr.count; j++) {
//        MyImageView *myImage = [_imageScrollView viewWithTag:889974 + j + 1];
        UIButton *smallBtn = [_smallImageScrollView viewWithTag:76445 + j + 1];
        [UIView animateWithDuration:0.2 animations:^{
            
//            myImage.frame = CGRectMake(spaceNum *space+ (_imageScrollView.width) *j, bigframe.origin.y, bigframe.size.width, bigframe.size.height);
            smallBtn.frame = CGRectMake((smallImageW  + 5.0f) *j, smallFrame.origin.y, smallFrame.size.width, smallFrame.size.height);//5.0f  是小图片的间距
            if (j == self.imageArr.count - 1) {
                lastAddBtn.frame = CGRectMake(smallBtn.maxX + space, smallBtn.y, smallImageW, smallImageW);
            }
            
        }];
        
//        myImage.tag = 889974 + j;
        smallBtn.tag = 76445 + j;
        
        
    }
}
//删除 服务器图片
- (void)removeImageFormNetWith:(NSNumber *)imageId
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:@{@"method" : @"app.branchCheck.del.img", @"img_id" :imageId}];
    
    [DataTool postWithUrl:HEAD_URL parameters:[DataTool addSignToDic:dict] success:^(id data) {
        id backData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers error:nil];
        NSLog(@"图片删除返回的数据%@",backData);
        
        if([backData[@"status"] isEqualToString:@"SUCCESS"]){
            [Tools showMessage:@"删除成功" view:self];
        }
    } fail:^(NSError *error) {
        NSLog(@"%@",error.localizedDescription);
    }];

}
- (void)takePictureInPhone1
{
    if(![Tools isAllowPhoto]){
        [Tools showMessage:@"APP无相册访问权限，请先设置!" view:self];
        return;
    }
    if (![QBImagePickerController isAccessible]) {
        [Tools showMessage:@"相机不可用哦" view:self];
    }
    QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsMultipleSelection = YES;
    imagePickerController.maximumNumberOfSelection = 20;//最大上传5张
    
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imagePickerController];
    [self presentViewController:navigationController animated:YES completion:NULL];
}
#pragma mark -- QBImage代理
- (void)imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets
{
//    _choosePicDataArray = [NSMutableArray array];
    
    //    NSLog(@"选择照片的数组个数%d",_choosePicDataArray.count);
//    [self dismissImagePickerController];
    if (self.presentedViewController) {
        [self dismissViewControllerAnimated:YES completion:^{
            UIImage *image;
            NSData *data;
             NSData *data1;
            UIImage *iamge;
//            NSLog(@"数组最后一个的类型 是===%@",[self.imageArr.lastObject class]);
              [SVProgressHUD showWithStatus:@"图片上传中"];
            for(int i = 0 ;i< assets.count; i ++){
                
//                @autoreleasepool {
                ALAssetRepresentation *resentation = [assets[i]  defaultRepresentation];
                
                image = [UIImage imageWithCGImage:[resentation fullScreenImage]];
                
                data = UIImageJPEGRepresentation(image, 0.5);
               
//                [self.imageArr addObject:data];
                
              
                //            [self.imageArr addObject:data];
//                MyImageView *imageview = [[MyImageView alloc] initWithFrame:CGRectMake(spaceNum *space + (_imageScrollView.width) * (self.imageArr.count), 2 *space , imageW, imageH)];
                
                UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake((smallImageW  + 5.0f) * self.imageArr.count, 0, smallImageW, smallImageW)];
                [btn addTarget:self action:@selector(clickSmallImage:) forControlEvents:UIControlEventTouchUpInside];
                //            btn.backgroundColor = [UIColor blackColor];
                //            UIImage *imag = [UIImage imageWithData:data];
                data1 = [self imageWithImage:image scaledToSize:CGSizeMake(smallImageW + 0.5, smallImageW + 0.5) withScale:0.1];
//                data = [self imageWithImage:image scaledToSize:CGSizeMake(imageview.width + 20  , imageview.height + 20) withScale:0.5];
                
//                  [_choosePicDataArray addObject:data];
                [self.imageArr addObject:data];
            
                [self.iamgeSmallArr addObject:data1];
                
                //            imageview.backgroundColor = [UIColor orangeColor];
                iamge = [UIImage imageWithData:data];
                
//                imageview.image = iamge;
                [btn setBackgroundImage:[UIImage imageWithData:data1] forState:UIControlStateNormal];//按钮使用的图片像素不高，压缩狠一点
                
                [_smallImageScrollView addSubview:btn];
//                [_imageScrollView addSubview:imageview];
                
                btn.tag = 76445 + self.iamgeSmallArr.count - 1 ;
//                imageview.tag = 889974 + self.imageArr.count - 1;
//                __weak ShowPhotoViewController *shwV =self;
//                imageview.block = ^(MyImageView *imageVie,BOOL isSelfSelected){
//                    popTips = [[PopTipView alloc] initWithFrame:CGRectMake(0, 0, [UIView getWidth:200], [UIView getHeight:120.0f])];
//                    popTips.tipsLabel.text = @"是否删除照片?";
//                    popTips.delegate = self;
//                    popTips.righTitle  = @"删除";
//                    popTips.leftTitle = @"取消";
//                    [popTips.leftButton setTitleColor:GRAYCOLOR forState:UIControlStateNormal];
//                    popTips.isShowImage = NO;
//                    [popTips showToView:shwV.view];
//                    selectedImageView = imageVie;
//                    //            imageSelected = isSelfSelected;
//                };
                
            }
//            _imageScrollView.contentSize = CGSizeMake(_imageScrollView.width *self.imageArr.count, _imageScrollView.height);
            _smallImageScrollView.contentSize = CGSizeMake((smallImageW + 5.0f)* (self.iamgeSmallArr.count + 1), smallImageW);
            [self changeLastBtnFrame];
            [self refreshIndexText];
          
            
          
            for (int i = 0; i < self.imageArr.count ; i++) {
                id type = self.imageArr[i];
                if ([type isKindOfClass:[ImageModel class]]) {
                    
                }else if ([type isKindOfClass:[NSData class]]){
                    
                    dispatch_sync(_globleQueue, ^{
                    
                        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
                        
                        NSLog(@"%@",indexPath);
                        //                      [SVProgressHUD showWithStatus:@"图片传输中"];
                        [self upLoadImageFirstWithIndexPath:indexPath];
                    });
                    isRecieveMemeriFlag = NO;
                }
                if(i == self.imageArr.count - 1){
                    [_collectionView reloadData];
                    _collectionView.contentSize = CGSizeMake(kScreenWidth * self.imageArr.count, _collectionView.height);
                    [SVProgressHUD dismiss];
                }
            }
            
            
        }];
        
        
     
    }
  
    //    NSLog(@"选择照片的数组个数 ===%ld",_choosePicDataArray.count);
    
}
- (void)changeLastBtnFrame
{
    if (self.iamgeSmallArr.count == 0) {
        lastAddBtn.frame = CGRectMake(0, 0, smallImageW, smallImageW);
    }else{
        lastAddBtn.frame = CGRectMake((smallImageW + 5.0) * self.iamgeSmallArr.count, 0, smallImageW, smallImageW);
    }
}

- (void)refreshIndexText
{
     CGFloat x = _collectionView.contentOffset.x;
    int page = floorf(x / _collectionView.width) + 1;
    _indexLabel.text = [NSString stringWithFormat:@"%d/%lu",page,(unsigned long)self.imageArr.count];
}
- (void)imagePickerControllerDidCancel1:(QBImagePickerController *)imagePickerController
{
    //    NSLog(@"*** imagePickerControllerDidCancel:");
    
    [self dismissImagePickerController];
}

- (void)dismissImagePickerController
{
    if (self.presentedViewController) {
        [self dismissViewControllerAnimated:YES completion:NULL];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView == _collectionView) {
    
    CGFloat x = scrollView.contentOffset.x;
    int page = floorf(x / _collectionView.width) + 1;
    _indexLabel.text = [NSString stringWithFormat:@"%d/%lu",page,(unsigned long)self.imageArr.count];
    }
//       [self refreshIndexText];
}


- (void)clickSmallImage:(UIButton *)sender
{
    long i = sender.tag - 76445;
    [UIView animateWithDuration:0.2 animations:^{
        _collectionView.contentOffset = CGPointMake(_collectionView.width * i, 0);

    }];
    [self refreshIndexText];
}
- (void)addPicture
{
    
      if(self.imageArr.count != 0){
    int  a = 0;
    for (int i = 0; i < self.imageArr.count ; i++) {
        id type = self.imageArr[i];
        if ([type isKindOfClass:[ImageModel class]]) {
            a ++;
        }else if ([type isKindOfClass:[NSData class]]){
            [Tools showMessage:@"请等待图片上传完成" view:self];
            return;
        }
        if (i == self.imageArr.count - 1) {
            if (self.imageArr.count == a) {
                popChooseCamera = [[PopTipView alloc] initWithFrame:CGRectMake(0, 0, [UIView getWidth:200.0f], [UIView getHeight:120.0f])];
                popChooseCamera.center = CGPointMake(kScreenWidth / 2.0f, kScreenHeight / 2.0f);
                
                popChooseCamera.tipsLabel.text = @"提示:请选择图片？";
                popChooseCamera.leftTitle = @"相机";
                popChooseCamera.righTitle = @"手机相册";
                popChooseCamera.delegate = self;
                [popChooseCamera showToView:self.view];
            }
        }
    }
      }else{
          popChooseCamera = [[PopTipView alloc] initWithFrame:CGRectMake(0, 0, [UIView getWidth:200.0f], [UIView getHeight:120.0f])];
          popChooseCamera.center = CGPointMake(kScreenWidth / 2.0f, kScreenHeight / 2.0f);
          
          popChooseCamera.tipsLabel.text = @"提示:请选择图片？";
          popChooseCamera.leftTitle = @"相机";
          popChooseCamera.righTitle = @"手机相册";
          popChooseCamera.delegate = self;
          [popChooseCamera showToView:self.view];
      }
}
- (void)setImageArr:(NSMutableArray *)imageArr
{
    _imageArr = imageArr;
   //23
}
- (void)setIamgeSmallArr:(NSMutableArray *)iamgeSmallArr
{
    _iamgeSmallArr = iamgeSmallArr;
}
- (void)jumpToRule
{
    RuleViewController2 *rulVC = [[RuleViewController2 alloc] init];
//    rulVC.inCameraChoose = YES;
    rulVC.ruleType = self.checkType;
    //    cv.check_id = ;
//    rulVC.inCameraChoose = NO;
    rulVC.branach_Id = self.branchId;
    rulVC.check_id = self.checkID;
    [self presentViewController:rulVC animated:YES completion:nil];
}
- (void)backToLastView
{
    
    if (self.chooseType == 1) {
         [self dismissViewControllerAnimated:YES completion:nil];
    }else{
        if(self.imageArr.count != 0){
        int  a = 0;
        for (int i = 0; i < self.imageArr.count ; i++) {
            id type = self.imageArr[i];
            if ([type isKindOfClass:[ImageModel class]]) {
                a ++;
            }else if ([type isKindOfClass:[NSData class]]){
                [Tools showMessage:@"请等待图片上传完成" view:self];
                return;
            }
            if (i == self.imageArr.count - 1) {
                if (self.imageArr.count == a) {
                    [self.navigationController popViewControllerAnimated:NO];
                }
            }
        }

        }else{
             [self.navigationController popViewControllerAnimated:NO];
        }
        
    }
   
}

#pragma mark --重拍
- (void)reTakePhoto
{
    if(self.imageArr.count == 0){
        return;
    }
    
    if(![Tools isAllowTakePhoto]){
        [Tools showMessage:@"APP无相机访问权限，请先设置!" view:self];
        return;
    }
//    for (int i = 0; i < self.imageArr.count ; i++) {
//        id type = self.imageArr[i];
//        if ([type isKindOfClass:[ImageModel class]]) {
//            
//        }else if ([type isKindOfClass:[NSData class]]){
//            
//            dispatch_sync(_globleQueue, ^{
//                NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
//                [SVProgressHUD showWithStatus:@"图片传输中"];
//                [self upLoadImageFirstWithIndexPath:indexPath];
//            });
//        }
//    }
    if(self.imageArr.count != 0){
        int  a = 0;
        for (int i = 0; i < self.imageArr.count ; i++) {
            id type = self.imageArr[i];
            if ([type isKindOfClass:[ImageModel class]]) {
                a ++;
            }else if ([type isKindOfClass:[NSData class]]){
                [Tools showMessage:@"请等待图片上传完成" view:self];
                return;
            }
            if (i == self.imageArr.count - 1) {
                if (self.imageArr.count == a) {
                    CGFloat x = _collectionView.contentOffset.x;
                    int page = floorf(x / _collectionView.width) ;
                    
                    //    MyImageView *myImage = [_collectionView viewWithTag:889974 + page];
                    UIButton *smallBtn = [_smallImageScrollView viewWithTag:76445 + page];
                    
                    //    if (myImage.iamgeID || myImage.fileName) {
                    //        [self addPicture];
                    id type = self.imageArr[page];
                    ImageModel *model = type;
                    NSLog(@"%@ llllllllllllshuzu ",type);
                    CameraViewController *cameraVC = [[CameraViewController alloc] init];
                    //        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:cameraVC];
                    cameraVC.isShouldBack = YES; //返回了
                    cameraVC.checkType = self.checkType;
                    cameraVC.branchId = self.branchId;
                    cameraVC.checkId = self.checkID;
                    cameraVC.isPush = NO;
                    [self presentViewController:cameraVC animated:YES completion:nil];
                    cameraVC.backBlock = ^(NSData *data,NSData *data1){
                        [DataTool uploadPic:data success:^(id data) {
                            [SVProgressHUD showInfoWithStatus:@"重拍中"];
                            //                                        NSLog(@"data %@",data);
                            //                        NSLog(@"图片大小%lu",(unsigned long)[data length]);
                            if ([data[@"status"] isEqualToString:@"ERROR"]) {
                                [Tools showMessage:data[@"msg"] view:self];
                                return ;
                            }else if([data[@"status"] isEqualToString:@"SUCCESS"]){
                                //                     [myImage sd_setImageWithURL:[NSURL URLWithString:data[@"data"][@"pic"]] placeholderImage:nil];
                                [smallBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:data[@"data"][@"pic"]] forState:UIControlStateNormal];
                                //                    self.pathBlock(data[@"data"][@"pic"]);
                                
                                NSString *STR = data[@"data"][@"pic"];
                                if (STR.length != 0 && STR) {
                                    
                                    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:@{@"method" : @"app.branchCheck.rephoto", @"img_id" :model.imageId,@"path" : STR}];
                                    //                    NSLog(@"重拍的参数%@",dict);
                                    [DataTool postWithUrl:HEAD_URL parameters:[DataTool addSignToDic:dict] success:^(id data) {
                                        [SVProgressHUD dismiss];
                                        id backData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers error:nil];
                                        NSLog(@"图片重拍返回的数据%@",backData);
                                        
                                        if([backData[@"status"] isEqualToString:@"SUCCESS"]){
                                            //                [Tools showMessage:@"重拍成功" view:self];
                                            NSString *urlStr = backData[@"data"][@"imgInfo"][@"url"];
                                            
                                            ImageModel *model = [[ImageModel alloc] init];
                                            model.file_name = backData[@"data"][@"imgInfo"][@"file_name"];
                                            model.imageId = backData[@"data"][@"imgInfo"][@"id"];
                                            model.url =  backData[@"data"][@"imgInfo"][@"url"];
                                            [self.imageArr replaceObjectAtIndex:page withObject:model];
                                            [_collectionView reloadData];
                                            [smallBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:urlStr] forState:UIControlStateNormal];
                                            [SVProgressHUD showSuccessWithStatus:@"重拍更新成功"];
                                            [SVProgressHUD dismiss];
                                        }else if([backData[@"status"] isEqualToString:@"ERROR"]){
                                            [SVProgressHUD showSuccessWithStatus:@"重拍更新失败"];
                                            
                                        }
                                        
                                        [SVProgressHUD dismiss];
                                    } fail:^(NSError *error) {
                                        [SVProgressHUD dismiss];
                                        NSLog(@"%@",error.localizedDescription);
                                    }];
                                }else{
                                    NSLog(@"1212121");
                                }
                                
                            }
                            NSLog(@"状态%@",data[@"status"]);
                            
                            
                        } fail:^(NSError *error) {
                            NSLog(@"%@",error);
                        }];
                        
                    };

                }
            }
        }
        
    }

    
    }

//    NSLog(@"图片的名字%@",myImage.fileName);
//    [myImage removeFromSuperview];
//    [smallBtn removeFromSuperview];
//    if (self.imageArr.count == 0 || self.iamgeSmallArr.count == 0  ) {
//        return;
//    }
//    [self.imageArr removeObjectAtIndex:page];
//    [self.iamgeSmallArr removeObjectAtIndex:page];
//    [self refreshShowWithIndex:page withBigFrame:myImage.frame withSmallFrame:smallBtn.frame];
//    [self changeLastBtnFrame];
//    [self refreshIndexText];
//    
//    _imageScrollView.contentSize = CGSizeMake(_imageScrollView.width *(self.imageArr.count), _imageScrollView.height);
//    _smallImageScrollView.contentSize = CGSizeMake((smallImageW + 5.0f)* (self.iamgeSmallArr.count + 1), smallImageW);
    
//    self.pathBlock = ^(NSString *path){
//        [SVProgressHUD show];
//         NSLog(@"重拍的参数%@",path);
//         NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:@{@"method" : @"app.branchCheck.rephoto", @"img_id" :myImage.iamgeID,@"path" :path}];
//        NSLog(@"重拍的参数%@",dict);
//        [DataTool postWithUrl:HEAD_URL parameters:[DataTool addSignToDic:dict] success:^(id data) {
//            [SVProgressHUD dismiss];
//            id backData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers error:nil];
//            NSLog(@"图片重拍返回的数据%@",backData);
//            
//            if([backData[@"status"] isEqualToString:@"SUCCESS"]){
//                //                [Tools showMessage:@"重拍成功" view:self];
//                NSString *urlStr = backData[@"data"][@"imgInfo"][@"url"];
//                
////                [myImage sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:nil];
//                NSLog(@"路径%@",urlStr);
//                myImage.fileName = backData[@"data"][@"imgInfo"][@"file_name"];
//                myImage.iamgeID = backData[@"data"][@"imgInfo"][@"id"];
////                [smallBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:urlStr] forState:UIControlStateNormal];
//                [SVProgressHUD showSuccessWithStatus:@"重拍更新成功"];
//                
//            }else if([backData[@"status"] isEqualToString:@"ERROR"]){
//                [SVProgressHUD showSuccessWithStatus:@"重拍更新失败"];
//                
//            }
//            
//             [SVProgressHUD dismiss];
//        } fail:^(NSError *error) {
//            [SVProgressHUD dismiss];
//            NSLog(@"%@",error.localizedDescription);
//        }];
//    };
//    if (myImage.iamgeID || myImage.fileName) {
//        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:@{@"method" : @"app.branchCheck.rephoto", @"img_id" :myImage.iamgeID,@"path" : myImage.imageUrl}];
//        [DataTool postWithUrl:HEAD_URL parameters:[DataTool addSignToDic:dict] success:^(id data) {
//            id backData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers error:nil];
//            NSLog(@"图片重拍返回的数据%@",backData);
//            
//            if([backData[@"status"] isEqualToString:@"SUCCESS"]){
////                [Tools showMessage:@"重拍成功" view:self];
//                [SVProgressHUD showSuccessWithStatus:@"重拍更新成功"];
//                [self addPicture];
//            }else if([backData[@"status"] isEqualToString:@"ERROR"]){
//                [SVProgressHUD showSuccessWithStatus:@"重拍更新失败"];
//                
//            }
//        } fail:^(NSError *error) {
//            NSLog(@"%@",error.localizedDescription);
//        }];
//    }




- (NSData *)imageWithImage:(UIImage*)image
              scaledToSize:(CGSize)newSize withScale:(CGFloat)scale;
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return UIImageJPEGRepresentation(newImage, scale);
}

//- (BOOL)prefersStatusBarHidden
//{
//    return YES;
//}
//- (UIStatusBarStyle)preferredStatusBarStyle
//{
//    return UIStatusBarStyleLightContent;
//}
//- (void)dealloc
//{
//    
//    dispatch_async(
//                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
//                   , ^{
//                       NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//                       
//                       NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
//                       //                       NSLog(@"files :%d",[files count]);
//                       for (NSString *p in files) {
//                           NSError *error;
//                           NSString *path = [cachPath stringByAppendingPathComponent:p];
//                           if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
//                               [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
//                           }
//                       };});
//    [[SDImageCache sharedImageCache] clearDisk];//清理磁盘
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    isRecieveMemeriFlag = YES;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
        //需要注意的是self.isViewLoaded是必不可少的，其他方式访问视图会导致它加载，在WWDC视频也忽视这一点。
        if (self.isViewLoaded && !self.view.window)// 是否是正在使用的视图
        {
            // Add code to preserve data stored in the views that might be
            // needed later.
            // Add code to clean up other strong references to the view in
            // the view hierarchy.
//            self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
            if(self.imageArr.count != 0){
                int  a = 0;
                for (int i = 0; i < self.imageArr.count ; i++) {
                    id type = self.imageArr[i];
                    if ([type isKindOfClass:[ImageModel class]]) {
                        a ++;
                    }else if ([type isKindOfClass:[NSData class]]){
                        [Tools showMessage:@"请等待图片上传完成" view:self];
                        return;
                    }
                    if (i == self.imageArr.count - 1) {
                        if (self.imageArr.count == a) {
                            self.view = nil;
                        }
                    }
                }
            }
        }
    }
//    dispatch_async(
//                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
//                   , ^{
//                       NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//                       
//                       NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
////                       NSLog(@"files :%d",[files count]);
//                       for (NSString *p in files) {
//                           NSError *error;
//                           NSString *path = [cachPath stringByAppendingPathComponent:p];
//                           if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
//                               [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
//                           }
//                       };});
     [[SDImageCache sharedImageCache] clearDisk];//清理磁盘
    
}
- (void)viewDidUnload
{
    [super viewDidUnload];

//    _globleQueue = nil;
//    _collectionView = nil;
//    _smallImageScrollView = nil;
//    self.imageArr = nil;
//    self.iamgeSmallArr = nil;
//    self.view = nil;
}
- (UIViewController *)childViewControllerForStatusBarHidden
{
    return nil;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
